package com.karrysong.blog_springboot.controller;

import com.karrysong.blog_springboot.util.QiniuUtil;
import com.karrysong.blog_springboot.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * @ClassName: UploadController
 * @Author: KarrySong
 * @Date: 2022/8/10 9:57
 * @Description:
 */
@RestController
@RequestMapping("/uploads")
public class UploadController {

    @Value("${webUrl}")
    private String webUrl;

    @PostMapping
    public Result upload(@RequestParam("image") MultipartFile file){
        String fileName = java.util.UUID.randomUUID().toString() + "." + StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        try {
            // 获取保存路径
            String path = getSavePath();
            File files = new File(path, fileName);
            File parentFile = files.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdir();
            }
            file.transferTo(files);
            return Result.success(webUrl + files.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.fail(20001,"上传失败");
    }

    public String getSavePath() {
        // 这里需要注意的是ApplicationHome是属于SpringBoot的类
        // 获取项目下resources/static/images路径
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());

        // 保存目录位置根据项目需求可随意更改
        return applicationHome.getDir().getParentFile()
                .getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\images";
    }

}
